from gpapi.googleplay import GooglePlayAPI
from accounts import Account
from gevent import monkey
import gevent
import socket
import requests
import math
import random

monkey.patch_socket()

base_dir = '/tmp/'
work_account_count = 2

def download_app(server, apk_name):
    print('\nstart downloading apk:', apk_name , '\n')
    data = server.download(apk_name)
    with open(base_dir + data['docId'] + '.apk', 'wb') as handle:
        for chunk in data.get('file').get('data'):
            handle.write(chunk)
    print('\nend downloading apk:', apk_name , '\n')

def assign_work(apps, count):
    random.shuffle(apps)
    apps_count = len(apps)
    step = int(math.ceil(apps_count / count))
    ret = [apps[i:i+step] for i in range(0, apps_count, step)]
    return ret

def start_work(apps, account):
    print(account)
    gp_ins = GooglePlayAPI(account['locale'], account['timezone'])

    print('\nLogging in with email and password, email:', account['email'] + '\n')
    gp_ins.login(account['email'], account['passwd'], None, None)
    for element in apps:
        download_app(gp_ins, element)
    print('\nemail:', account['email'] + ' end work\n')

if __name__ == '__main__':
    apps = [
     'com.xfx.surfvpn',
     'com.ted.android',
     'com.lenovo.anyshare.gps',
     'com.pixel.gun3d',
    ]

    work_set = assign_work(apps, work_account_count)

    account_ins = Account()
    account_info = account_ins.get_account(work_account_count)

    task_list = []
    for i in range(0, work_account_count):
        task_list.append(gevent.spawn(start_work, work_set[i], account_info[i]))

#    g_list = []
#    for element in apps:
#        g_list.append(gevent.spawn(download_app, element))
        
    gevent.joinall(task_list)
